from flask import render_template,redirect,url_for,request
from sqlalchemy import desc

from pms_app.models import *
from pms_app.forms import EmployeeForm


# from admin import admin
# @admin.route('/emp/list/')
# def emp_list():
#     items=db.session.query(Employee).limit(10)
#     return render_template('admin/emp-list-ajax.html',items=items)

from flask.views import MethodView
class EmployeeListView(MethodView):
    def get(self,page=1):
        items = Employee.query.paginate(page,per_page=10)
        return render_template('admin/emp-list.html', pagination=items)

class EmployeeDelView(MethodView):
    def get(self,id=None):
        if id:
            emp=db.session.query(Employee).get(id)  # .get（）只能针对主键id
            if emp:
                db.session.delete(emp)
                db.session.commit()
        return redirect(url_for('admin.emp_list'))  # admin. 前


class EmployeeCreateView(MethodView):
    def get(self):
        departments = db.session.query(Department).all()
        return render_template('admin/emp-detail.html',departments=departments)

    def post(self):
        emp=Employee(
            name=request.form.get('name'),
            gender= request.form.get('gender'),
            job=request.form.get('job'),
            birthdate=datetime.strptime(request.form.get('birthdate')[0:10],'%Y-%m-%d'),
            idcard=request.form.get('idcard'),
            address=request.form.get('address'),
            salary=float(request.form.get('salary')),
        )
        emp.department_id= int(request.form.get('department_id'))
        db.session.add(emp)
        db.session.commit()
        return redirect(url_for('admin.emp_list'))

# 使用表单对象form
class EmployeeCreateOrEdit(MethodView):
    '''新增或修改'''
    def get(self,id=None):
        emp = db.session.query(Employee).get(id)  if id else Employee()
            # emp=Employee.query.filter(Employee.id==id).first()
            # emp = db.session.query(Employee).get(id)  # get(主键值)
            # form.populate_obj(emp)
        form = EmployeeForm(request.form,obj=emp)
        form.department_id.choices=[(d.id,d.name) for d in Department.query.all()]
        return render_template('admin/emp-edit.html',form=form)

    def post(self,id=None):
        form=EmployeeForm(request.form)
        emp=db.session.query(Employee).get(id)  if id else Employee()
        form.populate_obj(emp)
        if not id:
            db.session.add(emp)
        db.session.commit()
        return redirect(url_for('admin.emp_list'))
